$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'lanling/school/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden: true},
            // { label: '后台账号id', name: 'sysId', index: 'sys_id', width: 80, align: "center" },
            {label: '学校名称', name: 'schoolName', index: 'school_name', width: 80, align: "center"},
            {label: '所在城市', name: 'cityName', index: 'city_name', width: 80, align: "center"},
            {label: '学校联系方式', name: 'schoolPhone', index: 'school_phone', width: 80, align: "center"},
            // {
            //     label: '学校logo', name: 'schoolLogo', index: 'school_logo', width: 80, align: "center",
            //     formatter: function (value) {
            //         return transImg(value);
            //     }
            // },
            {label: '经度', name: 'longitude', index: 'longitude', width: 80, align: "center"},
            {label: '纬度', name: 'latitude', index: 'latitude', width: 80, align: "center"},
            {label: '热门排序值', name: 'sortHotOrder', index: 'sort_hot_order', width: 80, align: "center"},
            {label: '创建时间', name: 'createDate', index: 'create_date', width: 80, align: "center"},
            {label: '更新时间', name: 'lastModifyDate', index: 'last_modify_date', width: 80, align: "center"}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
    $('#schoolDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: '350px', //高度
        minHeight: '200px',
        language: "zh_cn",
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../../sys/oss/upload',
        imageUploadParams: {id: "edit"},
        imagesLoadURL: '../../sys/oss/queryAll'
    })
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        school: {
            schoolLogo: ''
        },
        ruleValidate: {
            name: [
                {required: true, message: 'name不能为空', trigger: 'blur'},
                {max: 100, message: '请输入最多100位'}
            ]
        },
        q: {
            name: ''
        },
        backgroundAccounts: [],
        uploadList: [],
        visible: false,
        cityList: []
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.school = {
                schoolLogo: ''
            };
            vm.backgroundAccounts = [];
            vm.getBackgroundAccounts();
            vm.uploadList = [];
            $('#schoolDesc').editable('setHTML', '');
            vm.getCityList();
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getBackgroundAccounts();
            vm.getSchoolGallery(id);
            vm.getInfo(id);
            vm.getCityList();
        },
        getBackgroundAccounts: function () {
            $.get("../../sys/user/queryAll", function (r) {
                vm.backgroundAccounts = r.list;
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.school.id == null ? "lanling/school/save" : "lanling/school/update";
            vm.school.schoolImgList = vm.uploadList;
            vm.school.schoolDetail = $('#schoolDesc').editable('getHTML');

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(vm.school),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "lanling/school/delete",
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "lanling/school/info/" + id, function (r) {
                vm.school = r.school;
                $('#schoolDesc').editable('setHTML', vm.school.schoolDetail);
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessPicUrl: function (res, file) {
            vm.school.schoolLogo = file.response.url;
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        eyeImagePicUrl: function () {
            const url = vm.school.schoolLogo;
            eyeImage(url);
        },
        handleSuccess(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.picUrl = res.url;
            file.name = res.url;
            vm.uploadList.push(file);
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 10;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 10 张图片。'
                });
            }
            return check;
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            // 从 upload 实例删除数据
            const fileList = this.uploadList;
            this.uploadList.splice(fileList.indexOf(file), 1);
        },
        getSchoolGallery: function (id) {//获取学校顶部轮播图
            $.get("../../lanling/schoolpic/queryAll?schoolId=" + id, function (r) {
                vm.uploadList = r.list;
            });
        },
        getCityList: function () {//获取学校城市列表
            $.get("../../lanling/city/queryAll", function (r) {
                vm.cityList = r.list;
            });
        },
        cityChange: function (val) {
            vm.school.cityName = val.label.trim();
        },
        queryEvaluate: function () {//获取学校评价列表
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            openWindow({
                title: '评论列表',
                type: 2,
                content: '../lanling/schoolevaluate.html?schoolId=' + id
            })
        }
    },
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
    }
});